package com.itheima.reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Mapper.OrdersMapper;
import com.itheima.reggie.Pojo.*;
import com.itheima.reggie.Service.*;
import com.itheima.reggie.common.BaseContext;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
                               implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 订单支付
     * @param orders
     */
//  开启事务
    @Transactional
    @Override
    public void submit(Orders orders) {
        //获取当前用户id
        Long userid = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingquerywrapper = new LambdaQueryWrapper<>();
        shoppingquerywrapper.eq(userid!=null,ShoppingCart::getUserId,userid);
        List<ShoppingCart> shoppinglists = shoppingCartService.list(shoppingquerywrapper);
        //获取当前用户对象，得到用户信息
        User user = userService.getById(userid);
        //查询地址表，获取当前用户的默认地址
        LambdaQueryWrapper<AddressBook> addressqueryWrapper = new LambdaQueryWrapper<>();
        addressqueryWrapper.eq(userid!=null,AddressBook::getUserId,userid);
        addressqueryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(addressqueryWrapper);

        //给orders设置对应属性的值
        long id = IdWorker.getId();
        orders.setId(id);
        orders.setNumber(String.valueOf(id));
        orders.setStatus(2);
        orders.setUserId(userid);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);
        AtomicInteger amount=new AtomicInteger(0);
//      遍历购物车中的每条数据，算出总的金额数
        shoppinglists.stream().map((item) ->{
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return item;
        }).collect(Collectors.toList());
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
//      添加订单表，向订单表插入一条数据
        this.save(orders);

//      给购物车list集合中的每一个orderDetail赋上对应属性的值
        List<OrderDetail> list = shoppinglists.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            long id2 = IdWorker.getId();
            orderDetail.setId(id2);
            orderDetail.setOrderId(id);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setName(item.getName());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());
            return orderDetail;
        }).collect(Collectors.toList());
        //添加订单明细表。向订单明细表插入多条数据
        orderDetailService.saveBatch(list);

        //清空购物车
        shoppingCartService.remove(shoppingquerywrapper);
    }
}
